<?php

namespace app\admin\model\xmwms;

use think\Model;

/**
 * Product
 */
class Product extends Model
{
    // 表名
    protected $name = 'wms_product';

    /**
     * @var bool 自动写入时间戳字段
     */
    protected $autoWriteTimestamp = true;

    protected $append = [
        'warehouse_shelf_id_text'
    ];

    // 字段类型转换
    protected $type = [
        'deletetime' => 'timestamp:Y-m-d H:i:s',
    ];

    protected static function onAfterInsert($model)
    {
        if ($model->weigh == 0) {
            $pk = $model->getPk();
            $model->where($pk, $model[$pk])->update(['weigh' => $model[$pk]]);
        }
    }

    public function getImagesAttr($value): array
    {
        if ($value === '' || $value === null) return [];
        if (!is_array($value)) {
            return explode(',', $value);
        }
        return $value;
    }

    public function setImagesAttr($value): string
    {
        return is_array($value) ? implode(',', $value) : $value;
    }

    public function getWarehouseShelfIdTextAttr($value, $row): string
    {
        if (isset($row['warehouse_shelf_id']) && $row['warehouse_shelf_id'] > 0) {
            $model = new Warehouse();
            $data  = $model->where('id', $row['warehouse_shelf_id'])->find();
            if ($data['warehouse_type'] == 'warehouse_shelf') {
                $warehouse_area = $model->where('id', $data['pid'])->find();
                $warehouse      = $model->where('id', $warehouse_area['pid'])->value('name');
                return $warehouse . '/' . $warehouse_area['name'] . '/' . $data['name'];
            } elseif ($data['warehouse_type'] == 'warehouse_area') {
                $warehouse = $model->where('id', $data['pid'])->value('name');
                return $warehouse . '/' . $data['name'];
            } else {
                return $data['name'];
            }
        } else {
            return '';
        }
    }

    public function wmsBrand()
    {
        return $this->belongsTo(\app\admin\model\xmwms\Brand::class, 'brand_id', 'id');
    }

    public function wmsCategory()
    {
        return $this->belongsTo(\app\admin\model\xmwms\Category::class, 'category_id', 'id');
    }

    public function wmsUnit()
    {
        return $this->belongsTo(\app\admin\model\xmwms\Unit::class, 'unit_id', 'id');
    }

    public function wmsWarehouse()
    {
        return $this->belongsTo(\app\admin\model\xmwms\Warehouse::class, 'warehouse_shelf_id', 'id');
    }

    public function admin()
    {
        return $this->belongsTo(\app\admin\model\Admin::class, 'admin_id', 'id');
    }
}